package com.boesch.electroOffice.utils;

import java.io.Serializable;
import java.util.Iterator;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;

public class MessageUtils implements Serializable {
	
	private static final long serialVersionUID = -7083953675508694163L;

	public static void addErrorMessage(String msgText) {
		addErrorMessage(null, msgText);
	}

	public static void addErrorMessage(String clientId, String msgText) {
		msgText += " Bitte versuchen Sie es erneut oder wenden Sie sich an den Systemadministrator";
		addMessageInternal(clientId, msgText, FacesMessage.SEVERITY_ERROR);
	}

	public static void addInfoMessage(String msgText) {
		addInfoMessage(null, msgText);
	}

	public static void addInfoMessage(String clientId, String msgText) {
		addMessageInternal(clientId, msgText, FacesMessage.SEVERITY_INFO);
	}

	public static void addWarnMessage(String msgText) {
		addWarnMessage(null, msgText);
	}

	public static void addWarnMessage(String clientId, String msgText) {
		addMessageInternal(clientId, msgText, FacesMessage.SEVERITY_WARN);
	}
	
	private static void addMessageInternal(String clientId, String msgText, Severity severity) {
		FacesMessage fm = new FacesMessage(msgText);
		fm.setSeverity(severity);
		addMessageIfNotAddedYet(clientId, fm);
	}
	
	private static void addMessageIfNotAddedYet(String clientId, FacesMessage fm) {
		Iterator<FacesMessage> it = FacesContext.getCurrentInstance().getMessages(clientId);
		FacesMessage fmItem = null;
		while (it.hasNext()) {
			fmItem = it.next();
			if (fmItem.getSummary().equalsIgnoreCase(fm.getSummary())) {
				return;
			}
		}
		FacesContext.getCurrentInstance().addMessage(clientId, fm);
	}

	@Override
	public String toString() {
		return "MessageUtils [getClass()=" + getClass() + ", hashCode()="
				+ hashCode() + ", toString()=" + super.toString() + "]";
	}
}
